package com.example.springboot.config.aop;

import com.example.springboot.config.mysql.DataSourceContext;
import com.example.springboot.config.mysql.UseDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 用于切换数据库的通知
 *
 * @Author:ChenZhangKun
 * @Date: 2020/12/17 21:47
 */
@Aspect
@Component
@Slf4j
public class DataSourceAop {
    @Around("@annotation(useDataSource)")
    public Object routingWithDataSource(ProceedingJoinPoint joinPoint, UseDataSource useDataSource) throws Throwable {
        String value = useDataSource.value();
        log.info("【设置数据源{}】", value);
        // 设置数据源
        DataSourceContext.setDataSource(value);
        Object proceed = joinPoint.proceed();
        log.info("【清理数据源{}】", value);
        DataSourceContext.clearDataSource();
        return proceed;
    }
}
